package com.xinzhi.controller;

import com.xinzhi.pojo.User;
import com.xinzhi.service.IUserService;
import com.xinzhi.utils.JwtTokenUtil;
import com.xinzhi.utlis.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserLoginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 密码登录
     * @param user
     * @return
     */
    @PostMapping("/loginpassword")
    public Object loginpassword(@RequestBody User user){
        String phonenumber = user.getPhonenumber();
        String password = user.getPassword();
        if (StringUtils.isEmpty(phonenumber) | StringUtils.isEmpty(password)){
            return Result.error("手机号或密码不能为空");
        }
        Result loginpassword = userService.loginpassword(phonenumber, password);
        String token = jwtTokenUtil.generateToken(phonenumber);
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("token", token);
        map1.put("user", loginpassword);
        return map1;
    }

    /**
     * 验证码登录
     * @param user
     * @return
     */
    @RequestMapping("/logincode")
    public Object logincode(@RequestBody User user){
        String phonenumber = user.getPhonenumber();
        String password = user.getPassword();
        String message = user.getMessage();
        //拿出Redis中的验证码
        String code = (String)redisTemplate.opsForValue().get(user.getPhonenumber());
        if (message!=null&& code!=null && message.equals(code)){
            Result logincode = userService.logincode(phonenumber, password);
            String s = jwtTokenUtil.generateToken(phonenumber);
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("token", s);
            map1.put("user", logincode);
            return map1;
        }
        return Result.error("验证码错误");
    }
}
